package com.jiangli.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

public class SessionRandomUtil {
    // 存储随机ID序列的会话键名
    private static final String RANDOM_IDS_KEY = "DISH_RANDOM_IDS";

    /**
     * 保存随机ID序列到会话
     */
    public static void setRandomIds(List<Long> ids) {
        HttpSession session = getSession();
        if (session != null) {
            session.setAttribute(RANDOM_IDS_KEY, ids);
        }
    }

    /**
     * 从会话获取随机ID序列
     */
    @SuppressWarnings("unchecked")
    public static List<Long> getRandomIds() {
        HttpSession session = getSession();
        if (session != null) {
            return (List<Long>) session.getAttribute(RANDOM_IDS_KEY);
        }
        return null;
    }

    /**
     * 清除会话中的随机ID序列
     */
    public static void clearRandomIds() {
        HttpSession session = getSession();
        if (session != null) {
            session.removeAttribute(RANDOM_IDS_KEY);
        }
    }

    private static HttpSession getSession() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            return attributes.getRequest().getSession();
        }
        return null;
    }
}

